<?php
/**
 * Created by PhpStorm.
 * User: tengwei
 * Date: 2018/11/22
 * Time: 9:49 AM
 */
namespace common\logics\auth;

use common\widgets\Tool;
use yii\base\BaseObject;
use Yii;
use common\services\jwt\JWT;

class AuthLogic extends BaseObject implements IAuth
{
    public static $controller_area = ['area','operator-log','upload','sms-code'];
    /** @var \common\sources\read\adminuser\AdminUserAccess $RAdminUserAccess **/
    private $RAdminUserAccess;
    /** @var \common\sources\write\adminuser\AdminUserAccess $WAdminUserAccess **/
    private $WAdminUserAccess;
    /** @var \common\sources\read\loginrole\LoginRoleAccess $RLoginRoleAccess */
    private $RLoginRoleAccess;
    /** @var \common\sources\write\loginrole\LoginRoleAccess $WLoginRoleAccess */
    private $WLoginRoleAccess;
    /** @var \common\sources\read\loginpower\LoginPowerAccess $RLoginPowerAccess */
    private $RLoginPowerAccess;
    /** @var \common\sources\read\loginuserpower\LoginUserPowerAccess $RLoginUserPowerAccess */
    private $RLoginUserPowerAccess;
    /** @var \common\sources\write\loginuserpower\LoginUserPowerAccess $WLoginUserPowerAccess */
    private $WLoginUserPowerAccess;
    /** @var \common\sources\read\shop\ShopAccess $RShopAccess **/
    private $RShopAccess;
    /** @var \common\sources\read\taskcommod\TaskCommodAccess  $RTaskCommodAccess **/
    private $RTaskCommodAccess;
    /** @var \common\sources\read\taskorder\TaskOrderAccess  $RTaskOrderAccess  **/
    private $RTaskOrderAccess;
    /** @var \common\sources\read\bank\BankAccess $RBankAccess  **/
    private $RBankAccess;
    /** @var \common\sources\read\businesscash\BusinessCashAccess  $RBusinessCashAccess **/
    private $RBusinessCashAccess;
    /** @var \common\sources\read\buyprincipalcash\BuyPrincipalCashAccess  $RBuyPrincipalCashAccess **/
    private $RBuyPrincipalCashAccess;
    /** @var \common\sources\read\buypeppercash\BuyPepperCashAccess $RBuyPepperCashAccess  **/
    private $RBuyPepperCashAccess;
    /** @var \common\sources\read\taobao\TaoBaoAccess $RTaoBaoAccess  **/
    private $RTaoBaoAccess;

    public function init()
    {
        $this->RAdminUserAccess = Yii::$container->get('RAdminUserAccess');
        $this->RLoginRoleAccess = Yii::$container->get('RLoginRoleAccess');
        $this->WLoginRoleAccess = Yii::$container->get('WLoginRoleAccess');
        $this->RLoginPowerAccess = Yii::$container->get('RLoginPowerAccess');
        $this->RLoginUserPowerAccess = Yii::$container->get('RLoginUserPowerAccess');
        $this->WLoginUserPowerAccess = Yii::$container->get('WLoginUserPowerAccess');
        $this->RShopAccess = Yii::$container->get("RShopAccess");
        $this->RTaskCommodAccess = Yii::$container->get("RTaskCommodAccess");
        $this->RTaskOrderAccess = Yii::$container->get("RTaskOrderAccess");
        $this->RBankAccess = Yii::$container->get("RBankAccess");
        $this->RBusinessCashAccess = Yii::$container->get("RBusinessCashAccess");
        $this->RBuyPrincipalCashAccess = Yii::$container->get("RBuyPrincipalCashAccess");
        $this->RBuyPepperCashAccess = Yii::$container->get("RBuyPepperCashAccess");
        $this->RTaoBaoAccess = Yii::$container->get("RTaoBaoAccess");
        parent::init();
    }

    //获取系统当前角色列表
    public function getRoleList() {
        $roleList = $this->RLoginRoleAccess->getRoleList();
        if (!$roleList) {
            return Tool::returnJson([],200,"成功");
        }
        return Tool::returnJson($roleList,200,"成功");
    }

	//获取所有左边栏url
	public function getSubIndex($data) {
		//判断该用户是否存在
		$user = $this->RAdminUserAccess->getLoginUserById($data['login_id']);
		if (!$user) {
			return Tool::returnJson([], 401, "用户不存在");
		}
		//买号待审核
        $taobao_audit_count = $this->RTaoBaoAccess->getTaoBaoAuditCount(['audit_status'=>1]);
		//待审核店铺
        $shop_audit_count = $this->RShopAccess->getShopAuditCount(['audit_status'=>1]);
		//待审核主任务
        $taskCommod_audit_count = $this->RTaskCommodAccess->getTaskCommodAuditCount(['task_status'=>2]);
        //已经付款待审核订单
        $task_order_audit_count = $this->RTaskOrderAccess->getTaskOrderAuditCount(['order_status'=>2]);
        //买手提现账号待审核
        $buy_bank_audit_count = $this->RBankAccess->getBankAduitCount(["status"=>1]);
        //待打印快递单号统计
        $task_order_waiting_num = $this->RTaskOrderAccess->getTaskOrderAuditCount(['order_status'=>3]);
        //买手和商家提现记录审核
        $bus_cash_audit_count = $this->RBusinessCashAccess->getBusCashAuditCount(['cash_status'=>1]);
        //买手本金
        $buy_cash_audit_count = $this->RBuyPrincipalCashAccess->getBuyAuditCount(['status'=>1]);
        //买手佣金审核记录
        $buy_cash_pepper_audit_count = $this->RBuyPepperCashAccess->getAuditCount(['status'=>1]);

		//超级管理员
		if ($user['role'] === '1') {
			//获取所有的左边栏
			$allSubIndexNew = $this->RLoginPowerAccess->getSubIndex();
			foreach ($allSubIndexNew as &$item)
			{
			    if($item['powerid'] == 14)
			    {
			        $item['audit_count'] = $taobao_audit_count;
                }
                if($item['powerid'] == 15)
                {
                    $item['audit_count'] = $shop_audit_count;
                }
                if($item['powerid'] == 16)
                {
                    $item['audit_count'] = $taskCommod_audit_count;
                }
                if($item['powerid'] ==20)
                {
                    $item['audit_count'] = $task_order_audit_count;
                }
                if($item['powerid'] ==21)
                {
                    $item['audit_count'] = $buy_bank_audit_count;
                }
                if($item['powerid'] == 39)
                {
                    $item['audit_count'] = $task_order_waiting_num;
                }
                if($item['powerid'] == 45)
                {
                    $item['buy_audit_count'] = $buy_cash_audit_count + $buy_cash_pepper_audit_count;
                    $item['bus_audit_count'] = $bus_cash_audit_count ;
                }

            }

		} else {
			$all_power = $this->getUserPowerIds($user['id'], $user['role']);
			//获取所有的左边栏
			$allSubIndex = $this->RLoginPowerAccess->getSubIndex();
            foreach ($allSubIndex as &$item)
            {
                if($item['powerid'] == 14)
                {
                    $item['audit_count'] = $taobao_audit_count;
                }
                if($item['powerid'] == 15)
                {
                    $item['audit_count'] = $shop_audit_count;
                }
                if($item['powerid'] == 16)
                {
                    $item['audit_count'] = $taskCommod_audit_count;
                }
                if($item['powerid'] ==20)
                {
                    $item['audit_count'] = $task_order_audit_count;
                }
                if($item['powerid'] ==21)
                {
                    $item['audit_count'] = $buy_bank_audit_count;
                }
                if($item['powerid'] == 39)
                {
                    $item['audit_count'] = $task_order_waiting_num;
                }
                if($item['powerid'] == 45)
                {
                    $item['buy_audit_count'] = $buy_cash_audit_count + $buy_cash_pepper_audit_count;
                    $item['bus_audit_count'] = $bus_cash_audit_count ;
                }

            }
			$allSubIndexNew = [];
			if (!empty($all_power)) {
				foreach ($allSubIndex as $k => $value) {
					if (in_array($value['powerid'], $all_power)) {//该用户拥有该权限
						$allSubIndexNew[] = $value;
					} else {
						//unset($allSubIndex[$k]);
						//$value['is_use'] = 0;
					}
				}
			}
		}
		return Tool::returnJson($allSubIndexNew, 200, "成功");
	}

	//获取所有菜单及默认值 用户修改用户权限
	public function getUserPowerInfo($data) {
		//判断该用户是否存在
		$user = $this->RAdminUserAccess->getLoginUserById($data['login_id']);
		if (!$user) {
			return Tool::returnJson([], 401, "用户不存在");
		}

		$all_power = $this->getUserPowerIds($user['id'], $user['role']);

		//获取所有的左边栏
		$allSubIndex = $this->RLoginPowerAccess->getSubIndex();
		if (!empty($all_power)) {
			foreach ($allSubIndex as $k => $value) {
				if (in_array($value['powerid'], $all_power)) {//该用户拥有该权限
					$allSubIndex[$k]['is_use'] = 1;
				} else {
					$allSubIndex[$k]['is_use'] = 0;
				}
			}
		}
		return Tool::returnJson($allSubIndex, 200, "成功");
	}

    //用户添加权限
    public function addUserPower($data)
    {
        //判断该用户是否存在
        $user = $this->RAdminUserAccess->getLoginUserById($data['login_id']);
        if (!$user) {
            return Tool::returnJson([],401,"用户不存在");
        }
        $uinfo = $this->RLoginUserPowerAccess->getUserPower($data['login_id']);
        if($uinfo){
	        $addUserPower = $this->WLoginUserPowerAccess->editUserPower($data);
        }else{
	        $addUserPower = $this->WLoginUserPowerAccess->addUserPower($data);
        }
        if ($addUserPower === false) {
            return Tool::returnJson([],409,"设置失败");
        }
        return Tool::returnJson([],200,"设置成功");
    }

	//获取登录用户的权限
	public function loginUserPower($login_id) {
		//判断该用户是否存在
		$user = $this->RAdminUserAccess->getLoginUserById($login_id);
		if (!$user) {
			return Tool::returnJson([], 401, "用户不存在");
		}
		$all_power = $this->getUserPowerIds($user['id'], $user['role']);
		//获取登录用户可以展示的左边栏
		$viewSubIndex = $this->RLoginPowerAccess->viewSubIndex($all_power);
		return $viewSubIndex;
	}

    //检测用户是否有该方法权限
    public function checkPower()
    {
        //检查权限
        $controller = Yii::$app->controller->id;
        $action = Yii::$app->controller->action->id;
        $controller_action = $controller . '/' . $action;
        $pass_controller = in_array($controller,self::$controller_area);//不需要检查的控制器
        if ($pass_controller) {
            return true;
        }
        //获取登录用户的所有权限
       $access_key = Yii::$app->params['access_key'];
        $access_token = Yii::$app->request->headers->get('x-access-token');
        if (!$access_token) {
            return Tool::returnJson([], 601, 'token验证失败');
        }
        $workerInfo = (array)JWT::decode($access_token,$access_key,['HS256']);
        $loginid['login_id'] = $workerInfo['data']->userid;
        if (empty($loginid['login_id'])) {
            return Tool::returnJson([], 601, '用户id失效');
        }
	    //判断该用户是否存在
	    $user = $this->RAdminUserAccess->getLoginUserById($loginid['login_id']);
	    if (!$user) {
		    return Tool::returnJson([], 401, "用户不存在");
	    }
	    //超级管理员
	    if ($user['role'] === 1) {
		    return true;
	    }
        $loginUserPower = $this->loginUserPower($loginid);

        if (!empty($loginUserPower)) {
            $userPower = explode(',',implode(',',array_column($loginUserPower,'requstUrl')));
            $userPower = array_filter(array_unique($userPower));
        } else {
            $userPower = [];
        }

	    //默认权限
	    $defaultPower = [
		    'express-order/unprint-data-list',
		    'auth/get-sub-index',
		    'admin/sign',
		    'admin/logout',
	    ];
	    $userPower    = array_merge($userPower, $defaultPower);

        if (!in_array($controller_action,$userPower)) {
            return Tool::returnJson([], 100, '您没有此模块的权限');
        }
        return true;
    }

    //搜索管理员接口
    public function searchWorker($phone)
    {
        if (!empty($phone)) {
            $search = $this->RAdminUserAccess->getDetial($phone);
            $search = array($search);
        } else {
            $search = $this->RAdminUserAccess->getList();
        }
        return Tool::returnJson($search, $code = 200, '成功');
    }

    //添加新角色
    public function addRole($data)
    {
        if (empty($data['powerids']) || empty($data['rolename'])) {
            return Tool::returnJson([],401,'缺少参数');
        }
        $newRole = $this->WLoginRoleAccess->addRole($data);
        if (!$newRole) {
            return Tool::returnJson([],'200','角色添加失败');
        }
        return Tool::returnJson([],200,'角色添加成功');
    }


	/**
	 * editRole 编辑操作
	 *
	 * @param $data
	 *
	 * @author 中崋 (1291713293@qq.com)
	 * @date   2019/5/6
	 * @return false|string
	 */
	public function editRole($data) {
		if (empty($data['powerids']) || empty($data['rolename']) || empty($data['role_id'])) {
			return Tool::returnJson([], 401, '缺少参数');
		}
		//检测是否存在
		$info = $this->RLoginRoleAccess->getRoleInfo($data['role_id']);
		if (empty($info)) {
			return Tool::returnJson([], 401, '角色不存在');
		}

		$newRole = $this->WLoginRoleAccess->editRole($data);
		if ($newRole === false) {
			return Tool::returnJson([], '200', '角色修改失败');
		}
		return Tool::returnJson([], 200, '角色修改成功');
	}

	/**
	 * editRolePage 角色编辑页面数据
	 * @param $data 参数
	 * @author 中崋 (1291713293@qq.com)
	 * @date   2019/5/6
	 * @return false|string
	 */
	public function editRolePage($data) {
		if (empty($data['role_id'])) {
			//设置默认值状态
			$allSubIndex = $this->RLoginPowerAccess->getSubIndex();
			if (!empty($allSubIndex)) {
				foreach ($allSubIndex as &$value) {
					$value['is_use'] = 0;
				}
				unset($value);
			}
		} else {
			$data['info'] = $this->RLoginRoleAccess->getRoleInfo($data['role_id']);
			$rolePower    = $this->getRolePower($data['role_id']);

			//设置默认值状态
			$allSubIndex = $this->RLoginPowerAccess->getSubIndex();
			if (!empty($rolePower)) {
				foreach ($allSubIndex as &$value) {
					if (in_array($value['powerid'], $rolePower)) {
						$value['is_use'] = 1;
					} else {
						$value['is_use'] = 0;
					}
				}
				unset($value);
			}
		}
		return Tool::returnJson($allSubIndex, 200, "成功");
	}

	/**
	 * getUserPower 获取用户权限
	 * @param $user_id 用户ID
	 * @author 中崋 (1291713293@qq.com)
	 * @date   2019/5/6
	 * @return array|false|string|null
	 */
	public function getUserPower($user_id) {
		$user_power = $this->RLoginUserPowerAccess->getUserPower($user_id);
		if (!empty($user_power)) {
			$user_power = explode(",", $user_power);
		} else {
			$user_power = [];
		}
		return $user_power;
	}

	/**
	 * getRolePower 获取校色权限
	 * @param $role_id 角色ID
	 * @author 中崋 (1291713293@qq.com)
	 * @date   2019/5/6
	 * @return array|false|string|null
	 */
	public function getRolePower($role_id) {
		$role_power = $this->RLoginRoleAccess->getRolePower($role_id);
		if (!empty($role_power)) {
			$role_power = explode(",", $role_power);
		} else {
			$role_power = [];
		}
		return $role_power;
	}

	/**
	 * getUserPowerIds 获取用户所有权限 IDS
	 * @param $user_id 用户ID
	 * @param $role_id 角色ID
	 * @author 中崋 (1291713293@qq.com)
	 * @date   2019/5/6
	 * @return array
	 */
	public function getUserPowerIds($user_id, $role_id) {
		//该用户角色拥有的权限
		$role_power = $this->getRolePower($role_id);
		//该用户拥有的权限
		$user_power = $this->getUserPower($user_id);
		$all_power  = array_unique(array_merge($role_power, $user_power));
		return $all_power;
	}
}